﻿using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.RegularExpressions;
using Fuse8.DomainFramework.Domain;

namespace Fuse8.DomainFramework.DataAccess.SqlDatabase.Formatters
{
	internal class LikeFormattingService : IFormattingService
	{
		private static LikeFormattingService _instance;
		private static object _lock = new object();
		public static LikeFormattingService Instance
		{
			get
			{
				if (_instance != null)
				{
					return _instance;
				}
				lock(_lock)
				{
					return _instance = new LikeFormattingService();
				}
			}
		}
		public object FormatObject(object obj, ExpressionType? parentExpressionType)
		{
			if (! (obj is string))
			{
				throw new ArgumentOutOfRangeException("obj");
			}
			return Regex.Replace((string) obj, @"([\\%_])", @"\$1");
		}

		public Expression CreateFormatDelegate(Expression expression, ExpressionType? parentExpressionType)
		{
			var methodInfo = typeof(Regex).GetMethod("Replace", new[] { typeof(string), typeof(string), typeof(string) });
			var expr = Expression.Convert(expression, typeof (string));
			return Expression.Call(methodInfo, expr, Expression.Constant(@"([\\%_])"), Expression.Constant(@"\$1"));
		}
	}
}